/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package	dao;

import Hibernate.HibernateUtil;
import pojo.Author;
import pojo.Book;


import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class AuthorDAO extends AbstractDAO {

	@Override
	protected Class getPOJOClass() {
		// TODO Auto-generated method stub
		return Author.class;
	}
	
    public Author getAuthorByID(int id){
        Author author = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            author = (Author)session.get(Author.class, id);
        }
        catch(HibernateException ex){
            
        }
        finally{
            session.close();
        }
        return author;
    }
    public int insert(String authorName){
    	Author author = new Author();
    	author.setName(authorName);
    	Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.save(author);
			transaction.commit();
		} catch (HibernateException ex) {
			// Log the exception
			transaction.rollback();
		}
		finally {
			session.close();
			
		}
		return author.getAuthorId();
    }
    
    public List<Author> getTopAuthor(int n)
    {
    	List<Author> ds= null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		String hql = "select s from Author s join s.books b group by s.authorId order by count(b) desc " ;
		Query query = session.createQuery(hql);
		
		query.setMaxResults(n);
		ds =  query.list();
		session.close();
    	return ds;
    }
   
}
